//随机获取文章
$.ajax({
    type:'get',
    url:'/posts/random',
    success:function(response){
        var randomTpl = `
        {{each data}}
         <li>
        <a href="detail.html?id={{$value._id}}">
          <p class="title">{{$value.title}}</p>
          <p class="reading">阅读({{$value.meta.views}})</p>
          <div class="pic">
            <img src="{{$value.thumbnail}}" alt="">
          </div>
        </a>
      </li>
      {{/each}}
      `;
        var html = template.render(randomTpl,{data:response})
        $('#randomBox').html(html);
    }
});

//处理日期时间格式
function formateDate(date){
  //将日期时间字符串转换成日期对象
  date = new Date(date);
  return date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
}

//从浏览器获取查询参数
function getUrlParams(name){
  var paramsAry = location.search.substr(1).split('&');
  for(let i = 0;i<paramsAry.length;i++){
      var tem = paramsAry[i].split('=');
      if(tem[0]==name){
          return tem[1];
      }
  }
  return -1;
}

//获取最新评论
$.ajax({
  type:'get',
  url:'/comments/lasted',
  success:function(response){
    var lastedCommentsTpl=`
    {{each data}}
    <li>
    <a href="javascript:;">
      <div class="avatar">
        <img src="{{$value.author.avatar}}" alt="">
      </div>
      <div class="txt">
        <p>
          <span>{{$value.author.nickName}}</span>{{$imports.formateDate($value.createAt)}}说:
        </p>
        <p>{{$value.content}}</p>
      </div>
    </a>
  </li>
  {{/each}}
  `;
  var html = template.render(lastedCommentsTpl,{data:response});
  $('#lastedCommentsBox').html(html);
  }
})

//获取分类列表
$.ajax({
  type:'get',
  url:'/categories',
  success:function(response){
    var categoriesTpl=`
    {{each data}}
    <li>
    <a href="list.html?categoryId={{$value._id}}">
    <i class="fa {{$value.className}}"></i>{{$value.title}}
    </a></li>
    {{/each}}
    `;
    var html = template.render(categoriesTpl,{data:response});
    $('#navBox').html(html);
    $('#topNavBox').html(html);
  }
})

//获取搜索表单 添加表单提交事件
$('.search form').on('submit',function(){
  //获取到用户在表单中输入的关键字
  var keys = $(this).find('.keys').val();
  location.href="/search.html?key="+keys;
  return false;
});